package com.kedacom.ctsp.authz.oauth2.contract;

import com.alibaba.fastjson.JSON;
import com.jayway.restassured.module.mockmvc.RestAssuredMockMvc;
import com.kedacom.ctsp.authority.entity.SimpleUser;
import com.kedacom.ctsp.authority.entity.User;
import com.kedacom.ctsp.authority.service.UserService;
import com.kedacom.ctsp.authz.entity.AuthUser;
import com.kedacom.ctsp.authz.oauth2.controller.OAuth2ResourceController;
import com.kedacom.ctsp.authz.oauth2.core.OAuth2Authentication;
import com.kedacom.ctsp.authz.oauth2.entity.AccessToken;
import com.kedacom.ctsp.authz.oauth2.entity.SimpleAccessToken;
import com.kedacom.ctsp.authz.oauth2.service.AccessTokenService;
import com.kedacom.ctsp.authz.oauth2.service.OAuth2AuthenticationService;
import junit.framework.TestCase;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * api 接口 契约测试
 * rep2接口地址 http://rap2.ctsp.kedacom.com/repository/editor?id=26&mod=130
 */
@RunWith(SpringRunner.class)
public class ContractVerifierBase extends TestCase {

    @InjectMocks
    private OAuth2ResourceController oAuth2ResourceController;

    @MockBean
    private UserService userService;

    @MockBean
    private AccessTokenService accessTokenService;

    @MockBean
    private OAuth2AuthenticationService oAuth2AuthenticationService;

    /**
     * 初始化数据
     *
     * @throws Exception
     */
    @Before
    @Override
    public void setUp() throws Exception {

        MockitoAnnotations.initMocks(this);
        RestAssuredMockMvc.standaloneSetup(oAuth2ResourceController);

        // 模拟accessToken
        AccessToken accessToken = new SimpleAccessToken();
        accessToken.setOwnerId("1");

        Mockito.when(accessTokenService.getTokenByAccessToken("c27a87-a365-4326-8a91-dbc2bdd84896")).thenReturn(accessToken);

        // 模拟用户
        User user = new SimpleUser();
        user.setId("1");
        user.setUsername("admin");
        user.setName("超级管理员");

        Mockito.when(userService.get("1")).thenReturn(user);

        // 模拟返回值
        OAuth2Authentication oAuth2Authentication = new OAuth2Authentication();

        com.kedacom.ctsp.authz.oauth2.core.vo.AccessToken clientAccessToken =
                com.kedacom.ctsp.authz.oauth2.core.vo.AccessToken.builder().accessToken("c27a87-a365-4326-8a91-dbc2bdd84896").build();

        oAuth2Authentication.setAccessToken(clientAccessToken);

        AuthUser authUser = new AuthUser();
        authUser.setId(user.getId());
        authUser.setUsername(user.getUsername());

        oAuth2Authentication.setUser(authUser);

        // 模拟登陆
        Mockito.when(oAuth2AuthenticationService.loadUserByUsername(user.getUsername(), "rbac"))
                .thenReturn(oAuth2Authentication);

    }
}
